package com.inventory.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.inventory.exception.UserNotFoundException;
import com.inventory.persistence.User;
import com.inventory.persistence.UserExample;
import com.inventory.persistence.dao.UserMapper;

public class UserServiceDetailsImpl implements UserService, UserDetailsService {
	@Autowired
	private UserMapper userMapper;

	@Override
	public int createUser(User user) {
		user.setVersionStamp(1);
		return userMapper.insert(user);
	}

	@Override
	public int updateUser(User user) {
		user.setVersionStamp(user.getVersionStamp() + 1);
		return userMapper.updateByPrimaryKey(user);
	}

	@Override
	public int deleteUser(User user) {
		return userMapper.deleteByPrimaryKey(user.getOid());
	}

	@Override
	public List<User> getAllUsers() {
		UserExample example = new UserExample();
		example.createCriteria().andOidIsNotNull();
		return userMapper.selectByExample(example);
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public User getUserByUsername(String userName) throws UserNotFoundException {
		UserExample example = new UserExample();
		example.createCriteria().andUserNameEqualTo(userName);
		List<User> list = userMapper.selectByExample(example);
		if (list.isEmpty()) {
			throw new UserNotFoundException("User name not found!");
		}
		return list.get(0);
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		try {
			return getUserByUsername(username);
		} catch (UserNotFoundException e) {
			throw new UsernameNotFoundException(e.getMessage());
		}
	}

}
